package com.ruoyi.wechat.service.impl;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
@Service
public class QRCodeService {

    private static final String CHARSET = "UTF-8";
    private static final String FILE_TYPE = "png";

    /**
     * 生成二维码图片
     *
     * @param text  要编码到二维码中的文本
     * @param width 图片宽度
     * @param height 图片高度
     * @return 二维码图片的字节数组
     * @throws WriterException 二维码生成时可能发生的异常
     * @throws IOException     写入文件时可能发生的异常
     */
    public static byte[] generateQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        Path path = FileSystems.getDefault().getPath("tempQRCode.png");
        MatrixToImageWriter.writeToStream(bitMatrix, FILE_TYPE, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 将二维码图片写入HTTP响应
     *
     * @param response HTTP响应对象
     * @param text     要编码到二维码中的文本
     * @param width    图片宽度
     * @param height   图片高度
     * @throws WriterException 二维码生成时可能发生的异常
     * @throws IOException     写入响应时可能发生的异常
     */
    public static void writeQRCodeToResponse(HttpServletResponse response, String text, int width, int height) throws WriterException, IOException {
        byte[] qrCodeImage = generateQRCodeImage(text, width, height);
        response.setContentType("image/png");
        ServletOutputStream out = response.getOutputStream();
        out.write(qrCodeImage);
        out.flush();
        out.close();
    }
}